//
//  AzkarApi.m
//  Azkar
//
//  Created by 王易 on 2018/8/25.
//  Copyright © 2018年 CPX. All rights reserved.
//

#import "AzkarApi.h"
#import "AFNetworking.h"
#import <UIKit/UIKit.h>

/**
 祈福Api
 */
@implementation AzkarApi
+(RACSignal *)getData:(NSString *)method withParm:(NSDictionary *)parm
{
    
    
    RACSignal *signal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        
        NSString *url = [NSString stringWithFormat:@"%@%@",RootURL,method];

        [NetworkManagerV3 GETWithURL:url header:[self configHeader] params:parm success:^(id response) {
            
            [self successHandling:response with:subscriber];
        } failure:^(NSError *error) {
            
             [self errorHandling:error with:subscriber];
            
            
        }];
        
    return [RACDisposable disposableWithBlock:^{
        
    }];
    }];
    return signal;
}
+(RACSignal *)postData:(NSString *)method withParm:(NSDictionary *)parm
{
    RACSignal *signal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        
        NSString *url = [NSString stringWithFormat:@"%@%@",RootURL,method];
        
        NSDictionary *config = [self configHeader];
        [self POSTWithURL:url header:config params:parm success:^(id response) {
            [self successHandling:response with:subscriber];

        } failure:^(NSError *error) {
            [self errorHandling:error with:subscriber];
            
        }];
        
        return [RACDisposable disposableWithBlock:^{
            
        }];
    }];
    return signal;
}
+(RACSignal *)deleteData:(NSString *)method withParm:(NSDictionary *)parm
{
    RACSignal *signal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        
        NSString *url = [NSString stringWithFormat:@"%@%@",RootURL,method];
        
        NSDictionary *config = [self configHeader];
        [self DELETEWithURL:url header:config params:parm success:^(id response) {
            [self successHandling:response with:subscriber];
            
        } failure:^(NSError *error) {
            [self errorHandling:error with:subscriber];
            
        }];
        
        return [RACDisposable disposableWithBlock:^{
            
        }];
    }];
    return signal;
}
+ (void)POSTWithURL:(NSString *)url header:(NSDictionary *)config params:(id)params success:(Success)success failure:(Failure)failure{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20;
    for (NSString *key in config.allKeys) {
        [manager.requestSerializer setValue:config[key] forHTTPHeaderField:key];
    }
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        if (!data) {
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:@{@"msg":error.userInfo[@"NSLocalizedDescription"]}];
            failure(error1);
            return ;
        }
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        if (dic && dic[@"code"]&& [dic[@"code"] integerValue] == 0) {
            success(dic);
        }
        else{
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:dic?dic:@{@"msg":@"Unknow Error"}];
            failure(error1);
        }
        
    }];
}
+ (void)DELETEWithURL:(NSString *)url header:(NSDictionary *)config params:(id)params success:(Success)success failure:(Failure)failure{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20;
    for (NSString *key in config.allKeys) {
        [manager.requestSerializer setValue:config[key] forHTTPHeaderField:key];
    }
    [manager DELETE:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(error);
        
    }];
}

+ (void)successHandling:(id)response with:(id<RACSubscriber>) subscriber
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
    if (response[@"code"] && [response[@"code"] integerValue] == 0) {
        [subscriber sendNext:response[@"data"]];
    }else if(response[@"code"] && [response[@"code"] integerValue] == -2){
        UINavigationController *nav = [UINavigationController currentNC];
        Class loginCtrClass = NSClassFromString(@"LoginController");
        if (loginCtrClass) {
            UIViewController *ctr = [loginCtrClass new];
            ctr.hidesBottomBarWhenPushed = YES;
            [nav pushViewController:ctr animated:YES];
        }
        NSString *errorMessage = response[@"msg"];
//        [AlertTools showMessage:errorMessage ? errorMessage : @"data error"];
        NSError *error = [[NSError alloc] initWithDomain:NSURLErrorDomain code:-1001 userInfo:@{@"code":response[@"code"]}];
        [subscriber sendError:error];
    }
    else{
        NSString *errorMessage = response[@"msg"];
        [AlertTools showMessage:errorMessage ? errorMessage : @"data error"];
        [subscriber sendError:nil];
    }
    [subscriber sendCompleted];
}
+ (void)errorHandling:(NSError *)error with:(id<RACSubscriber>) subscriber
{
    NSString *errorMessage = error.userInfo[@"NSLocalizedDescription"];
    if (!errorMessage) {
        errorMessage = error.userInfo[@"msg"];
    }
    if (!errorMessage) {
        errorMessage = @"server error";
    }
    
    
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
    
    if ([error.userInfo[@"code"] integerValue] == -2) {
        UINavigationController *nav = [UINavigationController currentNC];
//        NSLog(@"%@",[UIApplication sharedApplication].keyWindow);
//        NSLog(@"%@",[UIApplication sharedApplication].keyWindow.rootViewController);
        
        Class loginCtrClass = NSClassFromString(@"LoginController");
        if (loginCtrClass) {
            UIViewController *ctr = [loginCtrClass new];
            ctr.hidesBottomBarWhenPushed = YES;
            [nav pushViewController:ctr animated:YES];
        }
        [AlertTools hideLoading];
    }
    else{
        [AlertTools showMessage:errorMessage];
    }
    [subscriber sendError:error];
    [subscriber sendCompleted];
//    [subscriber sendError:nil];
//    [subscriber sendCompleted];
}

+ (void)getMyAzkarListWithLimit:(NSInteger)limit offset:(NSInteger)offset success:(Success)success failure:(Failure)failure{
    NSString *url = [NSString stringWithFormat:@"%@%@",RootURL,MyAzkarPath];
    [NetworkManagerV3 GETWithURL:url header:[self header] params:@{@"offset":@(offset),@"limit":@(limit)} success:^(id response) {
        if([self dealWithResponse:response]){
            success(response[@"data"]);
        }
        else{
            NSError *error = [NSError errorWithDomain:APPResponseError code:10001 userInfo:response];
            failure(error);
        }
    } failure:^(NSError *error) {
        failure(error);
    }];
}

+ (void)shareBless:(NSString *)blessId success:(Success)success failure:(Failure)failure{
    NSString *url = [NSString stringWithFormat:@"%@%@%@",RootURL,BlessBlogPath,blessId];
    [NetworkManagerV3 PUTWithURL:url header:[self header] params:nil success:^(id response) {
//        if ([response[@"code"] integerValue] == -2) {
//            UINavigationController *nav = [UINavigationController currentNC];
//            Class loginCtrClass = NSClassFromString(@"LoginController");
//            if (loginCtrClass) {
//                UIViewController *ctr = [loginCtrClass new];
//                ctr.hidesBottomBarWhenPushed = YES;
//                [nav pushViewController:ctr animated:YES];
//            }
//        }
    } failure:^(NSError *error) {
        
    }];
}

+ (void)sharePBBless:(NSString *)blessId success:(Success)success failure:(Failure)failure{
    NSString *url = [NSString stringWithFormat:@"%@%@%@",RootURL,BlessPublicPath,blessId];
    [NetworkManagerV3 PUTWithURL:url header:[self header] params:nil success:^(id response) {
//        if ([response[@"code"] integerValue] == -2) {
//            UINavigationController *nav = [UINavigationController currentNC];
//            Class loginCtrClass = NSClassFromString(@"LoginController");
//            if (loginCtrClass) {
//                UIViewController *ctr = [loginCtrClass new];
//                ctr.hidesBottomBarWhenPushed = YES;
//                [nav pushViewController:ctr animated:YES];
//            }
//        }
    } failure:^(NSError *error) {
        
    }];
}

+ (void)readBless:(NSString*)blessId success:(Success)success{
    NSString *url = [NSString stringWithFormat:@"%@%@%@/read",RootURL,BlessBlogPath,blessId];
    [NetworkManagerV3 POSTWithURL:url header:[self header] params:nil success:^(id response) {
        if ([self dealWithResponse:response]) {
            success(response[@"data"]);
        }
        else{
            
        }
    } failure:^(NSError *error) {
        
    }];
}
+ (void)readPBBless:(NSString*)blessId success:(Success)success{
    NSString *url = [NSString stringWithFormat:@"%@%@%@/read",RootURL,BlessPublicPath,blessId];
    [NetworkManagerV3 POSTWithURL:url header:[self header] params:nil success:^(id response) {
        if ([self dealWithResponse:response]) {
            success(response[@"data"]);
        }
        else{
            
        }
    } failure:^(NSError *error) {
        
    }];
}

+ (NSDictionary*)configHeader{

//    return @{@"version":[BaseApi standard].version,@"Authorization":@"Token eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6OSwiZXhwIjoxNTQwMzQ2MzA5fQ.UottIZKLZreFbQpETP-XypEP35XpRgVKHTjIp334USc",@"language":[BaseApi standard].language };
    return [BaseApi header];
}
@end
